
let scopedInstances = new Map<any, any>();
(window as Any).__globalSingletonInstances__ = (window as Any).__globalSingletonInstances__ ?? new Map<any, any>();
let globalInstances = (window as Any).__globalSingletonInstances__

/**
 * 注册一个单实例服务
 * @param global 是否全局共享
 */
export function Singleton(global = false) {
  const instances = global ? globalInstances : scopedInstances;
  return function<T extends { new (...args: any[]): {} }>(Ctor: T) {
    return new Proxy(Ctor, {
      construct(t,args) {
        if (!instances.has(Ctor)) {
          instances.set(Ctor, new Ctor(args));
          console.log('instance ' + Ctor.name);
        }
        return instances.get(Ctor);
      }
    });
  }
}